import { SETADDRESS, SETADDRESSID } from '../mutation-type'
import http from '@/utils/axios'

function getToken () {
  if (sessionStorage.userInfo) {
    if (JSON.parse(sessionStorage.userInfo).token) {
      const token = JSON.parse(sessionStorage.userInfo).token
      return token
    }
  }
}

function mutationFunc (context, res) {
  if (res.data.code === 200) {
    context.commit('SETADDRESS', res.data.result)
    const arr = res.data.result.filter(item => {
      return item.isDefault === true
    })
    if (arr.length > 0) {
      context.commit('SETADDRESSID', arr[0].id)
    } else {
      context.commit('SETADDRESSID', '')
    }
  }
}

const module = {
  namespaced: true, // 命名空间
  state: {
    areaLists: [],
    chosenAddressId: '',
    disabledList: []
  },
  actions: {
    getAddressAction (context, payload) {
      http({
        url: '/vant/getarea',
        method: 'POST',
        data: { token: getToken() }
      }).then(res => {
        mutationFunc(context, res)
      })
    },
    modifyArea (context, payload) {
      // 修改默认地址
      http({
        url: '/vant/modify-area',
        method: 'POST',
        data: { user: payload.user, id: payload.id }
      }).then(res => {
        mutationFunc(context, res)
      })
    },
    deleteArea (context, payload) {
      http({
        url: '/vant/delete-area',
        method: 'POST',
        data: { user: getToken(), id: context.state.chosenAddressId }
      }).then(res => {
        mutationFunc(context, res)
      })
    },
    addArea (context, payload) {
      http({
        url: '/vant/add-area',
        method: 'POST',
        data: { content: { user: getToken(), ...payload } }
      }).then(res => {
        // console.log(res)
      })
    },
    modifyItem (context, payload) {
      // console.log(payload)
      http({
        url: '/vant/modify-item',
        method: 'POST',
        data: { user: getToken(), ...payload }
      }).then(res => {
        // mutationFunc (context, res)
      })
    }
  },
  mutations: {
    [SETADDRESS] (state, payload) {
      state.areaLists = payload
    },
    [SETADDRESSID] (state, payload) {
      state.chosenAddressId = payload
    }
  }
}

export default module
